package com.sfdk.admin.data.spritesheetEditor
{
    import com.sfdk.admin.data.RectangleEx;

    import flash.display.BitmapData;
    import flash.events.Event;
    import flash.geom.Point;

    [RemoteClass]
    public class TilePiece
    {
        private static var maxTileID:int;

        [Bindable]
        public var bitmapData:BitmapData;

        [Bindable]
        public var sourceRect:RectangleEx;
        private var _sourceBitmap:BitmapData;
        private var _id:int;

        public function TilePiece(sourceBitmap:BitmapData = null) {
            _sourceBitmap = sourceBitmap;
            setNewID();
        }

        public function init(bitmapData:BitmapData, sourceRect:RectangleEx):void {
            this.bitmapData = bitmapData;
            this.sourceRect = sourceRect;
            this.sourceRect.addEventListener(Event.CHANGE, regenerateImage);
        }

        public static function resetMaxID(value:int = 0):void {
            maxTileID = value;
        }

        public function setNewID():void {
            id = maxTileID + 1;
        }

        public function set id(value:int):void {
            maxTileID = Math.max(maxTileID, value);
            _id = value;
        }

        [Bindable]
        public function get id():int {
            return _id;
        }

        private var _fileName : String;

        public function set fileName(name : String) : void
        {
            _fileName = name;
        }

        public function get fileName():String {
            return _fileName;
        }

        public function regenerateImage(e:Event):void {
            var newBitmapData:BitmapData = new BitmapData(sourceRect.width, sourceRect.height, true, 0);
            newBitmapData.copyPixels(_sourceBitmap, sourceRect, new Point());
            bitmapData = newBitmapData;
        }

        public function clone():TilePiece {
            var tilePiece:TilePiece = new TilePiece();
            tilePiece.bitmapData = bitmapData;
            tilePiece.sourceRect = sourceRect;
            tilePiece.id = id;
            return tilePiece;
        }
    }

}